﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DiscoveryLogic.UI.Layouts.Converters;
using DiscoveryLogic.UI.Layouts.Models;
using DiscoveryLogic.UI.Layouts.Controls;
using System.Collections.Generic;
using Slider = DiscoveryLogic.UI.Layouts.WrappedControls.Slider;
using DiscoveryLogic.UI.Layouts.WrappedControls;
using DiscoveryLogic.UI.Layouts.DataAcccesses;
using DiscoveryLogic.DataServices.DataSources;
using System.Threading;
using System.Globalization;

namespace DiscoveryLogic.UI.Layouts.ContentScreens
{
    public partial class Enrollment : UserControl, IContentScreen 
    {
        #region Private Variables

        private MouseManager mouseEventManager;   

        private PieChart allocationPieChart;
        private PieChart samplePieChart;

        DiscoveryLogic.UI.Layouts.Models.UserProfile profile;

        int currentStep = 0;
        int lastStep = 4;

        FundsManager fundsManager;
        List<EnrollmentFund> listOfFunds;

        #endregion

        #region Constructors

        public Enrollment()
        {
            // Required to initialize variables
            InitializeComponent();


            // Initialize Variables
            mouseEventManager = new MouseManager();

            fundsManager = new FundsManager();

            // Set up some sample data for the funds panel
            listOfFunds = SetData();

            // Attach event handlers to button events etc
            AttachEventHandlers();

            // Create sliders for this scenario
            CreateSliderElements();

            // Create allocation pie chart
            allocationPieChart = new PieChart(new Point(200, 200), 100);

            // Set properties
            allocationPieChart.SetValue(Canvas.LeftProperty, -55.0);
            allocationPieChart.SetValue(Canvas.TopProperty, -80.0);
            allocationPieChart.SetValue(Canvas.NameProperty, "AllocationPieChart");

            allocationPieChart.AddSlice(0.3, 0.3, new EnrollmentFund(6, FundTypes.DomesticBonds, FindFundName(listOfFunds, FundTypes.DomesticBonds), 0, 0.3));
            allocationPieChart.AddSlice(0.5, 0.5, new EnrollmentFund(12, FundTypes.ForeignBonds, FindFundName(listOfFunds, FundTypes.ForeignBonds), 0, 0.5));
            allocationPieChart.AddSlice(0.2, 0.2, new EnrollmentFund(11, FundTypes.ShortTerm, FindFundName(listOfFunds, FundTypes.ShortTerm), 0, 0.2));
            allocationPieChart.HideFundValueLabels(true);

            allocationPieChart.DrawSlices();

            allocationPieChart.IsAllocationChart = true;
            allocationPieChart.contributionChanged += new EventHandler(OnPieChartContributionChanged);
            allocationPieChart.contributionChanging += new EventHandler(OnPieChartContributionChanging);
            allocationPieChart.callAttachFund = AttachFund;

            // Check contribution allocation
            CheckContributionAllocation(0);

            // Put in canvas
            EnrollmentAllocationPieCanvas.Children.Add(allocationPieChart);

            // Create Sample pie chart in step 3
            samplePieChart = new PieChart(new Point(200, 200), 100, true, false);

            // Set properties
            samplePieChart.AddSlice(0.3, 0.3, new EnrollmentFund(6, FundTypes.DomesticBonds, FindFundName(listOfFunds, FundTypes.DomesticBonds), 0, 0.3));
            samplePieChart.AddSlice(0.5, 0.5, new EnrollmentFund(12, FundTypes.ForeignBonds, FindFundName(listOfFunds, FundTypes.ForeignBonds), 0, 0.5));
            samplePieChart.AddSlice(0.2, 0.2, new EnrollmentFund(11, FundTypes.ShortTerm, FindFundName(listOfFunds, FundTypes.ShortTerm), 0, 0.2));
            samplePieChart.HideFundValueLabels(true);
            samplePieChart.HideFundNameLabels(true);

            samplePieChart.DrawSlices();

            samplePieChart.SetValue(Canvas.NameProperty, "SamplePieChart");

            // Add to canvas
            SamplePieCanvas.Children.Add(samplePieChart);

            // Attach EventHanders to Video Players
           //  Video1PlayBut.MouseLeftButtonUp += new MouseButtonEventHandler(Video1PlayBut_MouseLeftButtonUp);
          //   Video2PlayBut.MouseLeftButtonUp += new MouseButtonEventHandler(Video2PlayBut_MouseLeftButtonUp);
            Video2Encoded.MarkerReached +=new TimelineMarkerRoutedEventHandler(Video2Encoded_MarkerReached);            
        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Look through a list of funds for a matching fund type.
        /// If found, return the name of the fund
        /// </summary>
        /// <param name="listOfFunds"></param>
        /// <param name="fundType"></param>
        /// <returns></returns>
        private string FindFundName(List<EnrollmentFund> listOfFunds, FundTypes fundType)
        {
            string name =  fundType.ToString() + " Fund";

            for (int i = 0; i < listOfFunds.Count; i++)
            {
                if (listOfFunds[i].FundType == fundType)
                {
                    name = listOfFunds[i].FundName;
                    break;
                }
            }

            return name;
        }

        /// <summary>
        /// This helper method attachs event handlers to mouse events
        /// for different elements of the scenario
        /// </summary>
        private void AttachEventHandlers()
        {
            // Attach handlers for mouse manager signaling a screen change
            mouseEventManager.changeStep += new MouseManager.NextStepEventHandler(OnNextScreen);

            // Attach handlers for Next button            
            NextButton.Click += new RoutedEventHandler(mouseEventManager.OnMouseClickNext);
            BackButton.Click += new RoutedEventHandler(mouseEventManager.OnMouseClickBack);
            FinishButton.Click += new RoutedEventHandler(OnMouseClickFinish);


            // For gender radio button selection

            radioMale.Click += new RoutedEventHandler(OnGenderRadioButtonClick);
            radioFemale.Click += new RoutedEventHandler(OnGenderRadioButtonClick);

            /*
            GenderFemaleRadioButton.MouseEnter += mouseEventManager.OnMouseEnterHand;
            GenderFemaleRadioButton.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
            GenderFemaleRadioButton.MouseLeftButtonDown += new MouseButtonEventHandler(OnGenderRadioButtonClick);
                
             GenderMaleRadioButton.MouseEnter += mouseEventManager.OnMouseEnterHand;
            GenderMaleRadioButton.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
            GenderMaleRadioButton.MouseLeftButtonDown += new MouseButtonEventHandler(OnGenderRadioButtonClick);

             */

            // For Risk Question Mark
            RiskQuestionMark.MouseEnter += new MouseEventHandler(OnQuestionMarkMouseEnter);
            RiskQuestionMark.MouseLeave += new MouseEventHandler(OnQuestionMarkMouseLeave);

            // For New Account selection screen
            // 401 k button
            NewAccount401Canvas.MouseEnter += mouseEventManager.OnMouseEnterLift;
            NewAccount401Canvas.MouseEnter += mouseEventManager.OnMouseEnterHand;
            NewAccount401Canvas.MouseLeave += mouseEventManager.OnMouseLeaveLower;
            NewAccount401Canvas.MouseLeave += mouseEventManager.OnMouseLeaveArrow;

            NewAccount401Canvas.MouseLeftButtonUp += mouseEventManager.OnMouseClickNext;

            // 529 Account button
            NewAccount529Canvas.MouseEnter += mouseEventManager.OnMouseEnterLift;
            NewAccount529Canvas.MouseEnter += mouseEventManager.OnMouseEnterHand;
            NewAccount529Canvas.MouseLeave += mouseEventManager.OnMouseLeaveLower;
            NewAccount529Canvas.MouseLeave += mouseEventManager.OnMouseLeaveArrow;

            NewAccount529Canvas.MouseLeftButtonUp += new MouseButtonEventHandler(NewAccount529Canvas_MouseLeftButtonUp);

            // Personal Portfolio Account button
            NewAccountPortfolioCanvas.MouseEnter += mouseEventManager.OnMouseEnterLift;
            NewAccountPortfolioCanvas.MouseEnter += mouseEventManager.OnMouseEnterHand;
            NewAccountPortfolioCanvas.MouseLeave += mouseEventManager.OnMouseLeaveLower;
            NewAccountPortfolioCanvas.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
        }

        void radioFemale_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Creates the sliders for this scenario and sets properties
        /// </summary>
        private void CreateSliderElements()
        {
            // Get slider defaults obj from WS
            DiscoveryLogic.UI.Layouts.Models.SliderDefaults sliderDefaults = DiscoveryLogic.UI.Layouts.Models.SliderDefaultsManager.getSliderDefaults();

            // Place risk tolerence slider in
            RiskToleranceSlider.Minimum = 1;
            RiskToleranceSlider.Maximum = 10;

            // Set properties            
            
            // Set default value
            RiskToleranceSlider.Value = (profile.RiskTolerance);
            OnRiskSliderMoved(RiskToleranceSlider, null);

            // Put in canvas
            

            // Place percentage contribution slider in
            ContributionPercentSlider.Minimum = sliderDefaults.EnrollContribMin;
            ContributionPercentSlider.Maximum = sliderDefaults.EnrollContribMax;

            // Set properties
            //contributionPercentSlider.SetValue(Canvas.LeftProperty, 718);
            //contributionPercentSlider.SetValue(Canvas.TopProperty, 136.518);
            // contributionPercentSlider.sliderThumbMoved += new EventHandler(OnContributionSliderMoved);
            //ContributionPercentSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(OnContributionSliderMoved);
            // Set default values
            ContributionPercentSlider.Value = (profile.ContributionAmount);
            // JAIMERTODO: Confirm it is not needed .. see 3 lines below too 
            //  OnContributionSliderMoved(contributionPercentSlider, new EventArgs());

            // Set default value
            ContributionPercentSlider.Value = (sliderDefaults.EnrollContribDefault);
            // OnContributionSliderMoved(this, new EventArgs());

            // Put in canvas
            //SlidePanel.Children.Add(contributionPercentSlider);

            // Add vertical slider for the funds panel in step 4
            VerticalSlider vs = new VerticalSlider();
            FundsSlider.Children.Add(vs);
            vs.sliderMoved += new EventHandler(OnFundSliderMoved);
        }

        /// <summary>
        /// Create sample fund data for the fund panel in the allocation step
        /// </summary>
        private List<EnrollmentFund> SetData()
        {
            // Set user profile information.
            // Get user information from web servicey
            profile = DiscoveryLogic.UI.Layouts.Models.UserProfileManager.getUserProfile();

            // Fill textboxes with profile information
            FirstNameTextBox.Text = profile.FirstName;
            LastNameTextBox.Text = profile.LastName;
            DateOfBirthTextBox.Text = profile.DateOfBirth.ToShortDateString();
            SocialSecurityTextBox.Text = profile.SocialSecurityNumber.ToString();
            AnnualIncomeTextBox.DataContext = profile; //.AnnualIncome;



            // Get list of funds
            List<EnrollmentFund> listOfFunds = fundsManager.GetFunds();

            for(int i = 0; i < listOfFunds.Count; i++)
            {
                EnrollmentFund fundTab = listOfFunds[i];

                // Set properties
                fundTab.enrollmentFundDrag += new EventHandler(OnEnrollmentFundDrag);
                fundTab.enrollmentFundMouseDown += new EventHandler(OnEnrollmentFundMouseDown);
                fundTab.enrollmentFundMouseUp += new EventHandler(OnEnrollmentFundMouseUp);
                fundTab.SetValue(Canvas.LeftProperty, 0.0);
                fundTab.SetValue(Canvas.TopProperty, fundTab.Id * 40.0);
                fundTab.SetValue(Canvas.ZIndexProperty, FundPanel.Children.Count);

                // Add to canvas
                FundPanel.Children.Add(fundTab);
            }

            return listOfFunds;
        }

        /// <summary>
        /// This method changes the parent of a given fund from the fund panel
        /// to the pie chart panel while maintaining the same position on the screen.
        /// This is to facilitate dragging across containers.
        /// </summary>
        /// <param name="fund">The fund being dragged</param>
        private void FundPanelToPiePanel(EnrollmentFund fund, Canvas fromParent, Canvas toParent, MouseEventArgs e)
        {
            // Position of the fund
            double fundLeft = (double)fund.GetValue(Canvas.LeftProperty);
            double fundTop = (double)fund.GetValue(Canvas.TopProperty);

            // Distance from old parent and new parent
            Point fromPos = e.GetPosition(fromParent);
            Point toPos = e.GetPosition(toParent);

            // Differences
            Point deltaPos = new Point(fromPos.X - toPos.X, fromPos.Y - toPos.Y);
            Point newPos = new Point(fundLeft - deltaPos.X, fundTop - deltaPos.Y);

            // Set new values
            fund.SetValue(Canvas.LeftProperty, newPos.X);
            fund.SetValue(Canvas.TopProperty, newPos.Y);

            // Remove from old parent canvas
            fromParent.Children.Remove(fund);

            // Add to new parent canvas
            toParent.Children.Add(fund);
        }

        /// <summary>
        /// Given a fund, attach it to the fund panel canvas
        /// </summary>
        /// <param name="fund"></param>
        private void AttachFund(EnrollmentFund fund)
        {
            // Add fund to canvas

            if (fund.Parent == null)
            {
                FundPanel.Children.Add(fund);

                // Remove handlers if they exist because not sure which ones are there
                // and readd them
                fund.enrollmentFundDrag -= new EventHandler(OnEnrollmentFundDrag);
                fund.enrollmentFundMouseDown -= new EventHandler(OnEnrollmentFundMouseDown);
                fund.enrollmentFundMouseUp -= new EventHandler(OnEnrollmentFundMouseUp);

                fund.enrollmentFundDrag += new EventHandler(OnEnrollmentFundDrag);
                fund.enrollmentFundMouseDown += new EventHandler(OnEnrollmentFundMouseDown);
                fund.enrollmentFundMouseUp += new EventHandler(OnEnrollmentFundMouseUp);

                // Reset properties
                fund.ShrinkIcon();
                fund.SetValue(Canvas.LeftProperty, 0.0);
                fund.SetValue(Canvas.TopProperty, Convert.ToDouble(fund.Id * 40));
                fund.SetValue(Canvas.ZIndexProperty, fund.Id);
                fund.ResetPosition();
            } 
        }

        private void CheckContributionAllocation(double offset)
        {
            double percent = Math.Round((1 - allocationPieChart.TotalContributionPercent + offset) * 100);

            if (percent != 0)
            {
                ToAllocateExclamation.Opacity = 1;
                ToAllocateExclamationText.Opacity = 1;
                ToAllocateExclamationText.Text = percent + "% left to allocate";
            }
            else
            {
                ToAllocateExclamationText.Opacity = 0;
                ToAllocateExclamation.Opacity = 0;
            }
        }

        #endregion

        #region Public Methods

        public void FadeCanvasAnimation(bool show)
        {
            if (show == true)
            {
                FadeEnrollmentCanvasKeyFrame.Value = 1;
                FadeEnrollmentCanvas.Begin();
            }
            else
            {
                FadeEnrollmentCanvasKeyFrame.Value = 0;
                FadeEnrollmentCanvas.Begin();
            }
        }

        #endregion

        #region Event Handlers


            /// <summary>
            /// Handle the marker reached events for Video 2 (sample portfolio)
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void Video2Encoded_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
            {
                List<PieSlice> pieList = samplePieChart.GetPieSliceList();

                switch (e.Marker.Text)
                {
                    case "PreSectedFunds":
                        foreach (PieSlice slice in pieList)
                        {
                            slice.LiftSlice();
                        }
                        break;
                    case "ClosePres":
                        foreach (PieSlice slice in pieList)
                        {
                            slice.LowerSlice();
                        }
                        break;
                    case "FundG":
                        samplePieChart.GetPieSlice( FindFundName(listOfFunds, FundTypes.DomesticBonds) ).LiftSlice();
                        break;
                    case "FundGClose":
                        samplePieChart.GetPieSlice( FindFundName(listOfFunds, FundTypes.DomesticBonds )).LowerSlice();
                        break;
                    case "FundH":
                        samplePieChart.GetPieSlice( FindFundName(listOfFunds, FundTypes.ForeignBonds) ).LiftSlice();
                        break;
                    case "FundHClose":
                        samplePieChart.GetPieSlice( FindFundName(listOfFunds, FundTypes.ForeignBonds) ).LowerSlice();
                        break;

                    default:
                        break;
                }

            }

            void Video2PlayBut_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                if (Video2Encoded.CurrentState.Equals(MediaElementState.Playing))
                {
                    Video2Encoded.Pause();
                }
                else
                {
                    Video2Encoded.Play();
                }
            }

            void Video1PlayBut_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                if (Video1Encoded.CurrentState.Equals(MediaElementState.Playing))
                {
                    Video1Encoded.Pause();
                }
                else
                {
                    Video1Encoded.Play();
                }


            }

            /// <summary>
            /// When the contribution for a pie slice has changed,
            /// update the "%% Left to allocate" label
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnPieChartContributionChanged(object sender, EventArgs e)
            {
                CheckContributionAllocation(0);
            }

            private void OnPieChartContributionChanging(object sender, EventArgs e)
            {
                DiscoveryLogic.UI.Layouts.Models.CustomEventArgs args = (DiscoveryLogic.UI.Layouts.Models.CustomEventArgs)e;

                CheckContributionAllocation(args.ContributionOffset);
            }

            /// <summary>
            /// When the risk tolerance slider has changed in step 1,
            /// update the labels
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnRiskSliderMoved(object sender, RoutedEventArgs e)
            {            
                RiskQuestionMark.SetValue(Canvas.LeftProperty, 302.668);
                RiskTextLabelFrame.Width = 137.333;

                int risk = Convert.ToInt16(RiskToleranceSlider.Value);

                RiskTextLabel.Text = AppResources.GetRiskLevelString(risk);

                if (risk == 7)
                {
                    RiskTextLabelFrame.Width = 180;
                    RiskQuestionMark.SetValue(Canvas.LeftProperty, 345.335);
                }
                else if (risk == 4)
                {
                    RiskTextLabelFrame.Width = 160;
                    RiskQuestionMark.SetValue(Canvas.LeftProperty, 325.335);
                }

            }

          
            /// <summary>
            /// When the contribution slider in step 2 has changed, update the
            /// labels.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnContributionSliderMoved(object sender, RoutedEventArgs e)
            {
                double percent = ContributionPercentSlider.Percent;

                try
                {
                    DiscoveryLogic.UI.Layouts.Models.UserProfile profile = (DiscoveryLogic.UI.Layouts.Models.UserProfile)AnnualIncomeTextBox.DataContext;
                    int value = (int)profile.AnnualIncome;

                    ContributionAmountLabel.Text = Math.Round(value * percent).ToCurrency();
                }
                catch 
                {
                }

                ContributionPercentLabel.Text = Math.Round(percent, 2).ToPercentage();
            }

            /// <summary>
            /// When the fund panel slider is moved, move the canvas
            /// that the funds are on.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnFundSliderMoved(object sender, EventArgs e)
            {
                VerticalSlider vs = (VerticalSlider)sender;
                double lowestFundPosition = 0;

                // If there are children, find the lowest fund position
                for (int i = 0; i < FundPanel.Children.Count; i++)
                {
                    if ((double)FundPanel.Children[i].GetValue(Canvas.TopProperty) > lowestFundPosition)
                    {
                        lowestFundPosition = (double)FundPanel.Children[i].GetValue(Canvas.TopProperty);
                    }
                }

                // The min is the top of the canvas
                double fundPanelMin = 5;

                // The max is the lowest fund - the viewable area which is 4 funds
                // each fund is 40, so its maxID + 1 * 40 to get the max lenght then 
                // minus the viewable area which is 4 * 40.
                double fundPanelMax = (lowestFundPosition + 40) - (4 * 40);
                double distance = fundPanelMin - ((fundPanelMax - fundPanelMin) * vs.GetPercentage());

                FundPanel.SetValue(Canvas.TopProperty, distance);

            }

            /// <summary>
            /// As the fund is being dragged, check if its
            /// over a pie slice. If so, highlight the slice.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnEnrollmentFundDrag(object sender, EventArgs e)
            {
                MouseEventArgs args = (MouseEventArgs)e;
                EnrollmentFund fund = (EnrollmentFund)sender;
                // Check if it overlaps pie slices
                PieChart pc = EnrollmentAllocationPieCanvas.FindName("AllocationPieChart") as PieChart;
                bool hit = pc.HitTestHighlight(args);
            }

            /// <summary>
            /// When the user clicks a fund, change the funds
            /// parent from the fund panel to the enrollment canvas.
            /// This is to make it have the highest z index.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnEnrollmentFundMouseDown(object sender, EventArgs e)
            {
                MouseEventArgs args = (MouseEventArgs)e;
                EnrollmentFund fund = (EnrollmentFund)sender;

                FundPanelToPiePanel(fund, FundPanel, EnrollmentAllocationPieCanvas, args);
            }

            /// <summary>
            /// When the user releases a fund, check if it is over a pie slice.
            /// If not, move it back to fund panel
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnEnrollmentFundMouseUp(object sender, EventArgs e)
            {
                MouseEventArgs args = (MouseEventArgs)e;
                EnrollmentFund fund = (EnrollmentFund)sender;

                // Test if we're adding this fund
                PieChart pc = EnrollmentAllocationPieCanvas.FindName("AllocationPieChart") as PieChart;
                bool hit = pc.HitTestHighlight(args);
                if (hit == true)
                {
                    fund.SetValue(Canvas.LeftProperty, 0.0);
                    fund.SetValue(Canvas.TopProperty, 0.0);
                    EnrollmentAllocationPieCanvas.Children.Remove(fund);
                    pc.AddFund(fund);
                }
                else
                {
                    try
                    {
                        // Move fund from enrollment canvas back to fund list canvas
                        if (EnrollmentAllocationPieCanvas.Children.Contains(fund))
                        {
                            EnrollmentAllocationPieCanvas.Children.Remove(fund);
                        
                            // FIXED: Periodically a value out of range exception is thrown.
                            FundPanel.Children.Add(fund);
                            fund.SetValue(Canvas.LeftProperty, 0.0);
                            fund.SetValue(Canvas.TopProperty, Convert.ToDouble(fund.Id * 40));
                            fund.ResetPosition();
                        }
                    }
                    catch 
                    {
                    }
                }
            }

            /// <summary>
            /// Changes the position of the selection dot for the 
            /// two gender radio buttons (male/female) in step 1
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnGenderRadioButtonClick(object sender, RoutedEventArgs e)
            {
                // RadioButton source = sender as RadioButton;
                radioFemale.IsChecked = !radioMale.IsChecked;

                //TODO 
            }

            /// <summary>
            /// Shows the popup that is shown when the mouse
            /// hovers over the question mark
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnQuestionMarkMouseEnter(object sender, MouseEventArgs e)
            {
                RiskQuestionMarkPopup.Visibility = Visibility.Visible;
            }

            /// <summary>
            /// Hides the popup that is shown when the mouse
            /// hovers over the question mark
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnQuestionMarkMouseLeave(object sender, MouseEventArgs e)
            {
                RiskQuestionMarkPopup.Visibility = Visibility.Collapsed;
            }

            /// <summary>
            /// This method starts the screen scroll animation and
            /// also changes the opacity of the Step Labels at the top
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnNextScreen(object sender, DiscoveryLogic.UI.Layouts.Models.CustomEventArgs e)
            {
                if (currentStep != 0 &&
                    (e.NextStep == true && NextButton.Opacity == 0 ||
                    e.NextStep == false && BackButton.Opacity == 0)
                    )
                {
                    return;
                }    

            // Make sure videos are paused before continuing  
            // we do this by setting the buttons that drive it.. 

            Video1PlayBut.IsChecked = false;
            Video2PlayBut.IsChecked = false; 

             
            // Get current position of slider panel
            double leftPosition = (double)SlidePanel.GetValue(Canvas.LeftProperty);
            double previousStep = currentStep;

                // Determine which direction we are scrolling
                if (e.NextStep)
                {
                    ScrollSlidePanelKeyFrame.Value = leftPosition - 760;

                    // If we're moving from step 1 to step 2, save the user profile details
                    if (currentStep == 1)
                    {
                        double percent = RiskToleranceSlider.Percent;
                        int risk = Convert.ToInt32(RiskToleranceSlider.Minimum + (RiskToleranceSlider.Maximum - RiskToleranceSlider.Minimum) * percent);

                        profile.RiskTolerance = risk;
                    }
                    // If we`re moving from step 2 to 3, save contribution amount
                    else if (currentStep == 2)
                    {
                        double percent = ContributionPercentSlider.Percent;
                        profile.ContributionAmount = Math.Round(percent * 100);
                    }

                    // Increment the variable that keeps track of what step we are in
                    currentStep++;

                    // If we're at step 1 of enrollment, change the header
                    // from "New Account".
                    if (currentStep > 0)
                    {
                        NewAccountHeader.Opacity = 0;
                        EnrollmentHeader.Opacity = 1;
                    }
                }
                else
                {
                    ScrollSlidePanelKeyFrame.Value = leftPosition + 760;

                    // Decrement the variable that keeps track of what step we are in
                    currentStep--;

                    // If we're back at step 0 (New Account Selection),
                    // then change header back to "New Account" from "Enroll"
                    if (currentStep < 1)
                    {
                        NewAccountHeader.Opacity = 1;
                        EnrollmentHeader.Opacity = 0;
                    }
                }

                // Change opacity of previous Step label
                TextBlock tb = (TextBlock)EnrollmentCanvas.FindName("Step" + previousStep + "Label");
                if (tb != null)
                {
                    tb.Opacity = 0.3;
                }

                // Change opacity of current Step label
                tb = (TextBlock)EnrollmentCanvas.FindName("Step" + currentStep + "Label");
                if (tb != null)
                {
                    tb.Opacity = 1;
                }

                // Show elements on the screen's edge depending on which step we're at
                // This is to prevent elements from peeking out from the sides

                // video in step 2
                if (currentStep != 2)
                {
                    Video1OpacityAnimKeyFrame.Value = 0;
                    Video1OpacityAnim.Begin();
                }
                else
                {
                    Video1OpacityAnimKeyFrame.Value = 1;
                    Video1OpacityAnim.Begin();
                }

                // sample pie chart and video 2 in step 3
                if (currentStep != 3)
                {
                    SamplePieChartOpacityAnimKeyFrame.Value = 0;
                    SamplePieChartOpacityAnim.Begin();

                    Video2OpacityAnimKeyFrame.Value = 0;
                    Video2OpacityAnim.Begin();
                }
                else
                {
                    SamplePieChartOpacityAnimKeyFrame.Value = 1;
                    SamplePieChartOpacityAnim.Begin();

                    Video2OpacityAnimKeyFrame.Value = 1;
                    Video2OpacityAnim.Begin();
                }

                // pie chart in step 4
                if (currentStep != 4)
                {
                    AllocationPieChartOpacityAnimKeyFrame.Value = 0;
                    AllocationPieChartOpacityAnim.Begin();
                }
                else
                {
                    AllocationPieChartOpacityAnimKeyFrame.Value = 1;
                    AllocationPieChartOpacityAnim.Begin();
                }

                // Hide buttons
                //NextButton.Visibility = Visibility.Collapsed;
                //BackButton.Visibility = Visibility.Collapsed;
                //FinishButton.Visibility = Visibility.Collapsed;

                SetVisibleUsingWorkaround(NextButton, false);
                SetVisibleUsingWorkaround(BackButton, false);
                SetVisibleUsingWorkaround(FinishButton, false);

                // Start scroll animation
                ScrollSlidePanel.Begin();
            }

            /// <summary>
            /// When the scrolling animation for the screen stops
            /// this method is fired. This method sets the visibility
            /// of the back/next/finished buttons
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnScrollComplete(object sender, EventArgs e)
            {
                // If last step, make "Next" button invisible
                if (currentStep == lastStep)
                {
                    //NextButton.Visibility = Visibility.Collapsed;
                    FinishButton.Visibility = Visibility.Visible;

                    SetVisibleUsingWorkaround(NextButton, false);
                    SetVisibleUsingWorkaround(FinishButton, true);
                }
                else if (currentStep != 0)
                {
                    NextButton.Visibility = Visibility.Visible;
                    SetVisibleUsingWorkaround(NextButton, true);
                    //   FinishButton.Visibility = Visibility.Collapsed;
                    SetVisibleUsingWorkaround(FinishButton, false);
                }

                // If not first step, then make "Previous" button visible
                if (currentStep != 0)
                {
                    BackButton.Visibility = Visibility.Visible;
                    SetVisibleUsingWorkaround(BackButton, true);
                }
                else
                {
                    // BackButton.Visibility = Visibility.Collapsed;
                    SetVisibleUsingWorkaround(BackButton, false);
                }

                // Turn off foggy edges on the two steps that have pie
                // charts because the fog gets in the way of the pie
                // fund labels
                if (currentStep == 3 || currentStep == 4)
                {
                    FoggyEdgesBrush.StartPoint = new Point(-25, 219);
                }
                else
                {
                    FoggyEdgesBrush.StartPoint = new Point(0, 219);
                }
            }

            /// <summary>
            /// When the user clicks the finish button at the end
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnMouseClickFinish(object sender, RoutedEventArgs e)
            {
                // If finish button is invisible when the user clicks it,
                // don't show it.
                if (FinishButton.Opacity == 0)
                {
                    return;
                }

                if (enrollmentComplete != null)
                {
                    SetVisibleUsingWorkaround(FinishButton, false);
                    SetVisibleUsingWorkaround(BackButton, false);
                    enrollmentComplete(this, new EventArgs());
                }
            }


            public void SetVisibleUsingWorkaround(DiscoveryLogic.UI.Layouts.WrappedControls.Button btn, bool visibility)
            {
                if (visibility)
                {
                    btn.Opacity = 1.0;
                    btn.SetValue(Canvas.ZIndexProperty, 5);
                }
                else
                {
                    btn.Opacity = 0.0;
                    btn.SetValue(Canvas.ZIndexProperty, 0);
                }

            }

            /// <summary>
            /// On click of new 529 account label on the new account selection screen
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void NewAccount529Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                if (new529Enrollment != null)
                {
                    new529Enrollment(this, new EventArgs());
                }
            }


        #endregion

        #region Events

            public event EventHandler enrollmentComplete;

            public event EventHandler new529Enrollment;
            
        #endregion


        #region IContentScreen Members

        public void ScreenShowActions()
        {            
            // Reset to step 1
            double leftPosition = (double)SlidePanel.GetValue(Canvas.LeftProperty);
            SlidePanel.SetValue(Canvas.LeftProperty, 836.0);

            // Hide buttons
            SetVisibleUsingWorkaround(BackButton, false);
            SetVisibleUsingWorkaround(FinishButton, false);
            SetVisibleUsingWorkaround(NextButton, false);

            // Reset header
            NewAccountHeader.Opacity = 1;
            EnrollmentHeader.Opacity = 0;

            // Change opacity of previous Step indicator label
            TextBlock tb = (TextBlock)EnrollmentCanvas.FindName("Step" + currentStep + "Label");
            if (tb != null)
            {
                tb.Opacity = 0.3;
            }

            // Set step 1 label to be highlighted
            tb = (TextBlock)EnrollmentCanvas.FindName("Step1Label");
            if (tb != null)
            {
                tb.Opacity = 1;
            }

            currentStep = 0;

            Video1PlayBut.IsChecked = false;
            Video2PlayBut.IsChecked = false; 

        }

        public void ScreenHideActions()
        {            
            // Stop Videos
            Video1PlayBut.IsChecked = false;
            Video2PlayBut.IsChecked = false; 
        }

        #endregion

        private void Video_MediaEnded(object sender, RoutedEventArgs e)
        {
            MediaElement me = sender as MediaElement;
            if (me != null)
            {
                me.Position = TimeSpan.FromMilliseconds(0);
                if (me == Video1Encoded )
                {
                    Video1PlayBut.IsChecked = false; 
                }
                else if (me == Video2Encoded)
                {
                    Video2PlayBut.IsChecked = false;
                } 
            } 

            
        }

        private void Video1PlayBut_Checked(object sender, RoutedEventArgs e)
        {

            ToggleVideo(Video1PlayBut, Video1Encoded); 
              
        }

        private void Video2PlayBut_Checked(object sender, RoutedEventArgs e)
        {

            ToggleVideo(Video2PlayBut, Video2Encoded);

        }


        void ToggleVideo(VideoToggleButton button, MediaElement me)
        {
            if (button.IsChecked.Value)
            {

                me.Play();
            }
            else
            {
                me.Pause();
            }
        }
    }
}
